define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'tcfence/fence/index' + location.search,
                    add_url: 'tcfence/fence/add' + location.search,
                    edit_url: 'tcfence/fence/edit',
                    del_url: 'tcfence/fence/del',
                    multi_url: 'tcfence/fence/multi',
                    import_url: 'tcfence/fence/import',
                    table: 'fence',
                }
            });

            var table = $("#table");
            $(".btn-add").data("area", ["100%", "100%"]);


            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'areamanage_id', title: __('Areamanage_id'),visible: false},
                        {field: 'areamanage.name', title: __('Areamanage.name'), operate: 'LIKE'},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });
        },
        add: function () {
            Controller.api.bindevent();
            var istrue = false;
            /*A页面*/
            $(document).on('click', '.spec_add_btn', function (event) {
                var url = $(this).attr('data-url');
                if (!url) return false;
                var msg = $(this).attr('data-title');
                var width = $(this).attr('data-width');
                var height = $(this).attr('data-height');
                var area = [$(window).width() > 800 ? (width ? width : '800px') : '95%', $(window).height() > 600 ? (height ? height : '600px') : '95%'];
                var options = {
                    shadeClose: false,
                    shade: [0.3, '#393D49'],
                    area: area,
                    callback: function (value) {
                        /*打印回调函数*/
                        console.log(value)
                        /*处理逻辑*/
                        var jsons = JSON.stringify(value)
                        $('#c-datas').val(jsons)

                        if (istrue) {
                            document.getElementById("container_f").innerHTML = "";
                            $('#container_f').append('<div id=\'container\'></div>')
                        }
                        istrue = true;
                        /*TODO 地图渲染START*/
                        let geometrys = []
                        initMap();
                        /*获取数据*/
                        var map, editor;

                        function initMap() {
                            value[0]['paths'] = JSON.stringify(value[0]['paths']);
                            let f_arr = value

                            // 取值围栏一个坐标作为当前围栏中心点便于编辑显示
                            let center = {
                                lat: JSON.parse(f_arr[0].paths)[0].lat,
                                lng: JSON.parse(f_arr[0].paths)[0].lng
                            }
                            console.log(f_arr)
                            let s_arr = []
                            for (let index1 in f_arr) {
                                s_arr.push({paths: []})
                                for (let index2 in JSON.parse(f_arr[index1].paths)) {
                                    s_arr[index1].paths.push(new TMap.LatLng(JSON.parse(f_arr[index1].paths)[index2].lat, JSON.parse(f_arr[index1].paths)[index2].lng))
                                }
                            }

                            // 初始化地图
                            map = new TMap.Map("container", {
                                zoom: 16, // 设置地图缩放级别
                                center: new TMap.LatLng(center.lat, center.lng) // 设置地图中心点坐标
                            });

                            // 初始化几何图形及编辑器
                            editor = new TMap.tools.GeometryEditor({
                                map, // 编辑器绑定的地图对象
                                overlayList: [ // 可编辑图层
                                    {
                                        overlay: new TMap.MultiPolygon({
                                            map,
                                            styles: {
                                                highlight: new TMap.PolygonStyle({
                                                    color: 'rgba(255, 255, 0, 0.6)'
                                                })
                                            },
                                            geometries: s_arr
                                        }),
                                        id: 'polygon',
                                        selectedStyleId: 'highlight'
                                    }
                                ],
                                actionMode: TMap.tools.constants.EDITOR_ACTION.INTERACT, // 编辑器的工作模式
                                activeOverlayId: 'polygon', // 激活图层
                                selectable: true, // 开启点选功能
                                snappable: true // 开启吸附
                            });

                            // 监听删除、修改、拆分、合并完成事件
                            let evtList = ['delete', 'adjust', 'split', 'union'];
                            evtList.forEach(evtName => {
                                editor.on(evtName + '_complete', evtResult => {
                                    console.log(evtName, evtResult);
                                    delete evtResult.styleId;

                                    if (geometrys.length > 0) {
                                        for (let i = 0; i < geometrys.length; i++) {
                                            if (geometrys[i]['id'] == evtResult.id) {
                                                geometrys.splice(i, 1)
                                            }
                                        }
                                    }

                                    geometrys.push(evtResult)

                                    var jsons = JSON.stringify(geometrys)
                                    $('#c-datas').val(jsons)
                                });
                            });

                            // 监听拆分失败事件，获取拆分失败原因
                            editor.on('split_fail', (res) => {
                                alert(res.message);
                            });
                            // 监听合并失败事件，获取合并失败原因
                            editor.on('union_fail', (res) => {
                                alert(res.message);
                            });
                        }

                        /*TODO 地图渲染END*/
                    }
                };
                Fast.api.open(url, msg, options);
            });


            Form.api.bindevent($("form[role=form]"), function (data, ret) {
                //这里是表单提交处理成功后的回调函数，接收来自php的返回数据
                Fast.api.close(data);//这里是重点
                Toastr.success("成功");//这个可有可无
            }, function (data, ret) {
                Toastr.success("失败");
            });
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});